package kyssion.leetcode.num51_100;

public class code67_二进制求和 {
    public static void main(String[] args) {
        System.out.println(new code67_二进制求和().addBinary(
                "11","1"
        ));
    }
    public String addBinary(String a, String b) {
        if (a.length() < b.length()) {
            String i = a;
            a = b;
            b = i;
        }
        if (b.length() == 0) {
            return a;
        }
        char[] arrA = a.toCharArray();
        char[] arrB = b.toCharArray();
        int index = arrB.length - 1;
        int change = a.length()-b.length();
        int num = 0;
        while (index >= 0) {
            int i = arrA[index+change] - '0' + arrB[index] - '0' + num;
            if (i >= 2) {
                arrA[index+change] = (char) ('0'+i-2);
                num = 1;
            }else{
                arrA[index+change]= (char) ('0'+i);
                num = 0;
            }
            index--;
        }
        change--;
        while (change >= 0) {
            if (num + arrA[change] - '0' >= 2) {
                arrA[change] = (char) (num+arrA[change]-2);
            } else {
                arrA[change] = (char) (num + arrA[change]);
                num = 0;
                break;
            }
            change--;
        }
        a = new String(arrA);
        return num == 1 ? "1" + a : a;
    }
}
